﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Collections.Generic;

using Hangjing.Common;
using Hangjing.SQLServerDAL;
using Hangjing.Model;
using Hangjing.DBUtility;
using System.Text.RegularExpressions;
using Hangjing.WebCommon;

// 订单信息管理
// CopyRight (c) 2009-2010 HangJing Teconology. All Rights Reserved.
// zjf@ihangjing.com 
// 2011-06-10

public partial class Admin_shop_OrderDetail : AdminPageBase
{
    private string flag
    {
        get
        {
            object o = ViewState["flag"];
            return (o == null) ? "" : Convert.ToString(o);
        }
        set
        {
            ViewState["flag"] = value;
        }
    }

    private string SqlWhere
    {
        get
        {
            object o = ViewState["SqlWhere"];
            return (o == null) ? string.Empty : o.ToString();
        }
        set
        {
            ViewState["SqlWhere"] = value;
        }
    }


    private string orderid
    {
        get
        {
            object o = ViewState["orderid"];
            return (o == null) ? string.Empty : o.ToString();
        }
        set
        {
            ViewState["orderid"] = value;
        }
    }

    private int oid
    {
        get
        {
            object o = ViewState["oid"];
            return (o == null) ? 0 : Convert.ToInt32(o.ToString());
        }
        set
        {
            ViewState["oid"] = value;
        }
    }


    private int shopid
    {
        get
        {
            object o = ViewState["shopid"];
            return (o == null) ? 0 : Convert.ToInt32(o.ToString());
        }
        set
        {
            ViewState["shopid"] = value;
        }
    }

    /// <summary>
    /// 管理员编号
    /// </summary>
    private int uid
    {
        get
        {
            object o = ViewState["uid"];
            return (o == null) ? 0 : Convert.ToInt32(o.ToString());
        }
        set
        {
            ViewState["uid"] = value;
        }
    }


    protected void Page_Load(object sender, EventArgs e)
    {
        ValidatorSet validator = new ValidatorSet("Admin");
        validator.SetValidator();
        CheckRights("C");

        if (!IsPostBack)
        {
            //编辑
            string OrderId = HjNetHelper.GetQueryString("id");

            if (!string.IsNullOrEmpty(OrderId))
            {
                BindData(OrderId);
                hidDataId.Value = OrderId.ToString();

                string msg = "更新订单信息";
                pageType.Text = msg;
                oid = Convert.ToInt32(OrderId);
                uid = UserHelp.GetAdmin().ID;

            }
            else
            {
                pageType.Text = "新增订单";
                hidDataId.Value = "0";
            }
        }
    }

    Custorder bll = new Custorder();
    Foodlist orderfood_bll = new Foodlist();

    protected void BindData(string OrderId)
    {
        EnumHelper.OrderSourceToDropDownList(ddlsource);
        CustorderInfo info = bll.GetModel(Convert.ToInt32(OrderId));

        if (info != null)
        {
            if (info.TogoId == 0)
            {
                Response.Redirect("expressOrderDetail.aspx?id=" + info.Unid);
                return;
            }


            hidDataId.Value = info.Unid.ToString();
            hidTogoId.Value = info.TogoId.ToString();
            hidUserId.Value = info.UserId.ToString();

            tbOrderId.Text = info.orderid.ToString();
            tbTogoName.Text = info.TogoName;
            tbCustomerName.Text = info.CustomerName;
            tbUserName.Text = info.OrderRcver;
            tbTel.Text = info.OrderComm;
            tbAddress.Text = info.AddressText;

            tborderTime.Text = info.OrderDateTime.ToString();

            tbremark.Text = info.OrderAttach;

            this.lblpaymoney.Text = info.paymoney.ToString();

            tbUserId.Text = info.UserId.ToString();
            ddltime.Text = info.SendTime.ToShortTimeString() + "";
            flag = info.OrderStatus.ToString() + "";

            WebUtility.SelectValue(ddlPaystate, info.paystate.ToString());


            //
            if (info.OrderAddress != "")
            {
                tbadminname.Text = info.OrderAddress;

            }
            else
            {
                tradminname.Style.Add("display", "none");
            }

            tbsendstate.Text = WebUtility.TurnOrderSendState(info.sendstate.ToString());

            orderid = info.orderid;

            SqlWhere = "OrderComm ='" + info.OrderComm.ToString() + "' and custorder.unid <> " + OrderId + " ";

            this.rtpOrderlist.DataSource = bll.GetListFix(5, 1, SqlWhere, "OrderDateTime", 1);

            this.rtpOrderlist.DataBind();
            lbstatus.InnerHtml = "订单操作<font color='red'>(当前状态：" + WebUtility.TurnOrderState(info.OrderStatus.ToString()) + ")</font>";


            WebUtility.SelectValue(ddlsource, info.fromweb);



            tbshopdiscountmoney.Text = info.shopdiscountmoney.ToString();
            WebUtility.SelectValue(ddlIsShopSet, info.IsShopSet.ToString());
            lbshopnotice.InnerText = "商家说明：" + info.OrderAddrEx;
            tbcardpay.Text = info.cardpay.ToString();
            tbPrice.Text = info.OrderSums.ToString();
            tbcardid.Text = info.cardids;

            this.tbMergeorderremark.Text = info.Mergeorderremark.ToString();
            this.tbAdvance.Text = info.Advance.ToString();
            this.tbCommission.Text = info.Commission.ToString();
            hflocalinfo.Value = info.ReveVar2;
            hftid.Value = info.TogoId.ToString();
            WebUtility.SelectValue(ddlSystemUserId, info.SystemUserId.ToString());

            if (info.OrderChecker == 1)
            {
                btcheckaddress.Value = "地址已经复核";
                btcheckaddress.Disabled = true;
            }
            hfadminname.Value = UserHelp.GetAdmin().AdminName;

            damageRecordInfo damageinfo = new damageRecord().GetModel(info.orderid);
            if (damageinfo != null)
            {
                btadd.Style["display"] = "";
                btdel.Style["display"] = "";
                tbdamageRecordRemark.Text = damageinfo.remark;
                WebUtility.SelectValue(ddlresponsibleparty, damageinfo.responsibleparty);
            }

            getItem();

            shopid = info.TogoId;
            IList<CustorderInfo> orders = new List<CustorderInfo>();
            orders.Add(info);

            WebUtility.BindRepeater(rptorder, orders);
            WebUtility.SelectValue(ddlPaymode, info.paymode.ToString());
            tbpakcage.Text = info.Packagefee.ToString();

            tbDeliverGetSendFee.Text = info.DeliverGetSendFee.ToString();
            tbdelivergetfee_base.Text = info.delivergetfee_base.ToString();
        }
    }

    protected void btSave_Click(object sender, EventArgs e)
    {
        OperateLogManager<CustorderInfo> logmanager = new OperateLogManager<CustorderInfo>(UserHelp.GetAdmin().AdminName, TableENUM.Custorder.ToString());
        CustorderInfo info = bll.GetModel(HjNetHelper.GetQueryInt("id", 0));

        decimal olddistance = info.cardpay;
        decimal oldshopdiscountmoney = info.shopdiscountmoney;

        CustorderInfo oldmodel = logmanager.Clone(info);

        info.OrderAttach = WebUtility.InputText(tbremark.Text);
        info.AddressText = WebUtility.InputText(tbAddress.Text);
        info.OrderSums = Convert.ToDecimal(tbPrice.Text);
        info.paystate = Convert.ToInt32(ddlPaystate.SelectedValue);
        info.cardids = WebUtility.InputText(tbcardid.Text);
        info.shopdiscountmoney = Convert.ToDecimal(tbshopdiscountmoney.Text);

        info.Advance = Convert.ToDecimal(tbAdvance.Text);
        info.Commission = Convert.ToDecimal(tbCommission.Text);
        info.Mergeorderremark = WebUtility.InputText(tbMergeorderremark.Text);
        info.cardpay = Convert.ToDecimal(tbcardpay.Text);
        info.SystemUserId = Convert.ToInt32(ddlSystemUserId.SelectedValue);
        info.OrderComm = WebUtility.InputText(tbTel.Text);
        info.delivergetfee_base = Convert.ToDecimal(tbdelivergetfee_base.Text);


        //判断权限
        int _rs = WebUtility.checkOperator(3);
        if (_rs == 0)
        {
            AlertScript.RegScript(this.Page, this.UpdatePanel1, "alert('无操作权限','success','true',5);init();hideload_super();");
            return;
        }


        if (bll.Update(info) > 0)
        {
            new OrderManager().TellDeliverUpdateInfo(info);
            IList<deliverlogInfo> logs = logmanager.Compare(oldmodel, info, info.orderid);
            if (logs.Count > 0)
            {
                DataTable dt = CollectionHelper.ConvertTo(logs, "deliverlog");
                SQLHelper.SqlBulkCopyData(dt);
            }
            if (olddistance != info.cardpay || oldshopdiscountmoney != info.shopdiscountmoney)//距离有修改，更新配送费相关信息
            {
                decimal delivergetfee = 0;
                decimal delivergetfee_base = 0;

                PointsInfo shop = new Points().GetModel(info.TogoId);

                delivergetfee_base = bll.curDeliverGetSendFee(shop, info, out delivergetfee);

                if (delivergetfee_base == 0)
                {
                    delivergetfee_base = info.shopdiscountmoney;
                }

                WebUtility.excutesql("UPDATE dbo.Custorder SET delivergetfee_base = " + delivergetfee_base + ",DeliverGetSendFee=" + delivergetfee + " WHERE orderid = '" + info.orderid + "'");
                if (info.deliverid > 0)
                {
                    new Custorder().curDeliverGetSendFee(orderid);
                }
                //商家的收费要 变化 加上原来，减去现在的


                if (info.TogoId > 0 && Math.Abs(info.shopdiscountmoney - oldshopdiscountmoney) > 0)
                {
                    TogoAddMoneyLogInfo shopmoney = new TogoAddMoneyLogInfo();
                    shopmoney.UserId = info.TogoId;
                    shopmoney.AddMoney -= (info.shopdiscountmoney - oldshopdiscountmoney);
                    shopmoney.Inve2 = "订单修改地址，费用变化："+orderid;
                    bll.ShopAccount(shopmoney);
                }

            }


            AlertScript.RegScript(this.Page, UpdatePanel1, "tipsWindown('更新订单','text:更新订单信息成功','250','150','true','','true','text');hideload_super();");
            BindData(info.Unid.ToString());

        }
        else
        {
            AlertScript.RegScript(this.Page, UpdatePanel1, "tipsWindown('更新订单','text:更新订单信息失败','250','150','true','','true','text')");
        }
    }


    protected void feeupdate_Click(object sender, EventArgs e)
    {

        CustorderInfo info = bll.GetModel(HjNetHelper.GetQueryInt("id", 0));

        //判断权限
        int _rs = WebUtility.checkOperator(3);
        if (_rs == 0)
        {
            AlertScript.RegScript(this.Page, this.UpdatePanel1, "alert('无操作权限','success','true',5);init();hideload_super();");
            return;
        }


        decimal delivergetfee = 0;
        decimal delivergetfee_base = 0;

        PointsInfo shop = new Points().GetModel(info.TogoId);

        delivergetfee_base = bll.curDeliverGetSendFee(shop, info, out delivergetfee);

        if (delivergetfee_base == 0)
        {
            delivergetfee_base = info.shopdiscountmoney;
        }

        WebUtility.excutesql("UPDATE dbo.Custorder SET delivergetfee_base = " + delivergetfee_base + ",DeliverGetSendFee=" + delivergetfee + " WHERE orderid = '" + info.orderid + "'");
        if (info.deliverid > 0)
        {
            new Custorder().curDeliverGetSendFee(orderid);
        }

        AlertScript.RegScript(this.Page, UpdatePanel1, "tipsWindown('更新订单','text:更新订单信息成功','250','150','true','','true','text');hideload_super();");
        BindData(info.Unid.ToString());


    }





    /// <summary>
    /// 更新用户坐标
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void chagelocation_Click(object sender, EventArgs e)
    {
        string OrderId = HjNetHelper.GetQueryString("id");
        CustorderInfo order = bll.GetModel(OrderId);
        string latlng = "{\"ulat\":\"" + WebUtility.InputText(hidLat.Value) + "\",\"ulng\":\"" + WebUtility.InputText(this.hidLng.Value) + "\",\"slat\":\"" + WebUtility.InputText(this.hfshoplat.Value) + "\",\"slng\":\"" + WebUtility.InputText(hfshoplng.Value) + "\"}";
        WebUtility.excutesql("UPDATE dbo.Custorder SET ReveVar2 = '" + latlng + "' WHERE unid =  " + OrderId);
        //如果这个这个手机号没有此地址，要增加一个，

        EAddressInfo addrmodel = new EAddressInfo();
        addrmodel.Receiver = order.OrderRcver;
        addrmodel.Address = order.AddressText;
        addrmodel.BuildingID = 0;
        addrmodel.Phone = order.OrderComm;
        addrmodel.Mobilephone = order.OrderComm;
        addrmodel.UserID = uid;
        addrmodel.AddTime = DateTime.Now;
        addrmodel.Pri = 0;
        addrmodel.Lat = WebUtility.InputText(hidLat.Value);
        addrmodel.Lng = WebUtility.InputText(this.hidLng.Value);

        int userid = new EAddress().SaveUserAndAddress(addrmodel);


        string url = "OrderDetail.aspx?id=" + OrderId;
        AlertScript.RegScript(this.Page, UpdatePanel1, "alert('更新用户地址信息成功');gourl('" + url + "');");

    }

    /// <summary>
    /// 地址复核
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void checkaddress_Click(object sender, EventArgs e)
    {
        string OrderId = HjNetHelper.GetQueryString("id");

        string sql = "UPDATE dbo.Custorder SET OrderChecker = 1 ,settleuser = '" + UserHelp.GetAdmin().AdminName + "' WHERE unid = " + OrderId;
        WebUtility.excutesql(sql);

        string url = "OrderDetail.aspx?id=" + OrderId;
        AlertScript.RegScript(this.Page, UpdatePanel1, "alert('地址复核成功');gourl('" + url + "');");

    }


    /// <summary>
    /// 状态修改
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void updatestate_Click(object sender, EventArgs e)
    {
        string dataid = HjNetHelper.GetQueryString("id");
        Button bt = (Button)sender;

        CustorderInfo info = bll.GetModel(Convert.ToInt32(dataid));
        int newstate = Convert.ToInt32(bt.CommandArgument);

        bll.AddOrderRecord(info.orderid, newstate, UserHelp.GetAdmin().AdminName, "管理员修改订单信息:订单详细界面");

        string sql = "UPDATE dbo.Custorder SET OrderStatus = " + newstate + "  WHERE unid = " + dataid;
        WebUtility.excutesql(sql);



        switch (newstate)
        {
            case 2:
                break;
            case 3:

                bll.AddPoint(orderid);
                new OrderServiceImpl().manComplete(orderid, info.deliverid);

                break;
            case 6:

                bll.OrderCancelRefundForShop(info.orderid);

                break;
        }

        {
            NoticeHelper notice = new NoticeHelper(Context, info.deliverid.ToString());
            notice.sendOrderByDeliveryid(info.deliverid);
        }
        {
            NoticeHelper notice = new NoticeHelper(Context, info.TogoId.ToString());
            notice.send2ShopByShopid();
        }


        string url = "OrderDetail.aspx?id=" + dataid;
        AlertScript.RegScript(this.Page, UpdatePanel1, "alert('状态操作成功');gourl('" + url + "');");

    }

    protected IList<FoodlistInfo> getproduct(object oid)
    {
        return orderfood_bll.GetAllByOrderID(oid.ToString());
    }

    /// <summary>
    /// 确认损单
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void adddamage_Click(object sender, EventArgs e)
    {
        string dataid = HjNetHelper.GetQueryString("id");
        string orderid = WebUtility.InputText(tbOrderId.Text);
        damageRecordInfo info = new damageRecordInfo();
        info.dId = 0;
        info.orderid = orderid;
        info.addtime = DateTime.Now;
        info.remark = WebUtility.InputText(tbdamageRecordRemark.Text);
        info.opadmin = UserHelp.GetAdmin().AdminName;
        info.responsibleparty = WebUtility.InputText(ddlresponsibleparty.SelectedValue, true);
        info.reveint1 = 0;
        info.reveint2 = 0;
        info.revevar1 = "";
        info.revevar2 = "";
        info.revevar3 = WebUtility.InputText(ddlresponsibleparty.SelectedItem.Text);

        new damageRecord().Add(info);

        string sql = "UPDATE  dbo.Custorder SET ReveInt2 = 1 WHERE unid = " + dataid;
        WebUtility.excutesql(sql);

        string url = "OrderDetail.aspx?id=" + dataid;
        AlertScript.RegScript(this.Page, UpdatePanel1, "alert('操作成功');gourl('" + url + "');");

    }

    /// <summary>
    /// 取消损单
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void delamage_Click(object sender, EventArgs e)
    {
        string dataid = HjNetHelper.GetQueryString("id");

        string orderid = WebUtility.InputText(tbOrderId.Text);

        string sql = " DELETE damageRecord WHERE orderid = '" + orderid + "'";

        sql += ";UPDATE  dbo.Custorder SET ReveInt2 = 0 WHERE unid = " + dataid;
        WebUtility.excutesql(sql);


        WebUtility.excutesql(sql);



        string url = "OrderDetail.aspx?id=" + dataid;
        AlertScript.RegScript(this.Page, UpdatePanel1, "alert('操作成功');gourl('" + url + "');");

    }



    protected void getItem()
    {
        IList<FoodlistInfo> food_list = new List<FoodlistInfo>();
        food_list = orderfood_bll.GetAllByOrderID(orderid);

        rptsubItem.DataSource = food_list;
        rptsubItem.DataBind();
    }

    protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName == "del")
        {
            //判断权限
            int _rs = WebUtility.checkOperator(4);
            if (_rs == 0)
            {
                AlertScript.RegScript(this.Page, this.UpdatePanel1, "alert('无操作权限','success','true',5);init();");
                return;
            }
            if (orderfood_bll.DelList(e.CommandArgument.ToString()) > 0)
            {
                AlertScript.RegScript(this, UpdatePanel1, "alert('删除成功！');");
                int dataid = HjNetHelper.GetQueryInt("id", 0);

                new OrderManager().TellDeliverUpdateInfo(dataid);


                getItem();
            }
            else
            {
                AlertScript.RegScript(this, UpdatePanel1, "alert('删除失败，请重试！');");
            }
        }
    }

    protected void GridView_RowEditing(object sender, GridViewEditEventArgs e)
    {
        rptsubItem.EditIndex = e.NewEditIndex;
        getItem();
    }

    protected void GridView_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
    {
        rptsubItem.EditIndex = -1;
        getItem();
    }

    protected void GridView_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {
        //判断权限
        int _rs = WebUtility.checkOperator(3);
        if (_rs == 0)
        {
            AlertScript.RegScript(this.Page, this.UpdatePanel1, "alert('无操作权限','success','true',5);init();");
            return;
        }

        FoodlistInfo food = new FoodlistInfo();
        food.Unid = Convert.ToInt32(((Label)rptsubItem.Rows[e.RowIndex].FindControl("lb_id")).Text.Trim());
        food.FoodName = ((TextBox)rptsubItem.Rows[e.RowIndex].FindControl("tbFoodName")).Text.Trim();
        food.FCounts = Convert.ToInt32(((TextBox)rptsubItem.Rows[e.RowIndex].FindControl("tbFCounts")).Text.Trim());
        food.FoodPrice = Convert.ToDecimal(((TextBox)rptsubItem.Rows[e.RowIndex].FindControl("tbFoodPrice")).Text.Trim());
        food.OldPrice = food.FoodPrice;


        if (orderfood_bll.Update(food) > 0)
        {
            int dataid = HjNetHelper.GetQueryInt("id", 0);
            new OrderManager().TellDeliverUpdateInfo(dataid);
            AlertScript.RegScript(Page, UpdatePanel1, "alert('编辑成功！');");
            getItem();
        }
        else
        {
            AlertScript.RegScript(Page, UpdatePanel1, "alert('编辑失败，请重试！');");
        }
        rptsubItem.EditIndex = -1;
        getItem();
    }

    /// <summary>
    /// 添加商品
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void addfood_Click(object sender, EventArgs e)
    {

        int dataid = HjNetHelper.GetQueryInt("id", 0);

        FoodlistInfo food = new FoodlistInfo();
        food.Unid = 0;
        food.FoodName = WebUtility.InputText(tbFoodName1.Text);
        food.FCounts = Convert.ToInt32(WebUtility.InputText(tbFCounts1.Value));
        food.FoodPrice = Convert.ToDecimal(WebUtility.InputText(tbFoodPrice1.Value));
        food.OldPrice = food.FoodPrice;
        food.adddate = DateTime.Now;
        food.COUnid = dataid;
        food.orderid = orderid;
        food.InUse = "Y";
        food.Remark = "";
        food.TogoId = shopid;

        orderfood_bll.Add(food);

        new OrderManager().TellDeliverUpdateInfo(dataid);


        string url = "OrderDetail.aspx?id=" + dataid;
        AlertScript.RegScript(this.Page, UpdatePanel1, "alert('操作成功');gourl('" + url + "');");

    }


}

